package com.yzc.filter;

import com.yzc.Authentication.JwtAuthenticationToken;
import com.yzc.execption.ZcException;
import com.yzc.result.Result;
import com.yzc.util.JwtUtil;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yzc.result.ResultCodeEnum.INVALID_TOKEN;

@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final RedisTemplate<String, String> redisTemplate;

    public JwtAuthenticationFilter(JwtUtil jwtUtil, RedisTemplate<String, String> redisTemplate) {
        this.jwtUtil = jwtUtil;
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        String authHeader = request.getHeader("Authorization");
        String token = jwtUtil.resolveToken(authHeader);                //从请求头（如 Authorization: Bearer <token>）或 Cookie 中提取 JWT。

        if (token == null) {                                            // 如果未找到 token，直接放行请求，交给后续过滤器或控制器处理。此时用户被视为“未认证”。
            filterChain.doFilter(request, response);
            return;
        }
        try {
            Result<Void> voidResult = jwtUtil.validateToken(token);
            if (voidResult.getCode() != Result.success().getCode()) {
                throw new BadCredentialsException("无效的token");
            }
            String tokenKey = "token:" + token;
            if (Boolean.FALSE.equals(redisTemplate.hasKey(tokenKey))) {  // 检查 Redis 中是否存在该用户的 token
                throw new BadCredentialsException("令牌已失效");
            }
            Map<Object, Object> tokenDetails = redisTemplate.opsForHash().entries(tokenKey);

            String userId = (String) tokenDetails.get("user_id");       //提取用户ID
            String userTokenKeys = "user_tokens:" + userId;
            String username = (String) tokenDetails.get("username");    // 提取用户名
            String rolename = (String) tokenDetails.get("rolename");    // 提取角色名

            Double score = redisTemplate.opsForZSet().score(userTokenKeys, token);

            if (score == null) {
                redisTemplate.delete(tokenKey);             //清理无效的token
                throw new ZcException(INVALID_TOKEN);
            }

            // 将角色字符串转换为权限集合
            List<GrantedAuthority> authorities = convertRolesToAuthorities(rolename);

            // 创建认证对象并设置权限
            /*UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(username, null, authorities);*/

            JwtAuthenticationToken authentication = new JwtAuthenticationToken(userId, username, authorities);

            SecurityContextHolder.getContext().setAuthentication(authentication);


        } catch (JwtException | AuthenticationException e) {
            SecurityContextHolder.clearContext();
            throw e;
        } catch (Exception e) {
            throw new ServletException(e);
        }

        filterChain.doFilter(request, response);
    }

    private List<GrantedAuthority> convertRolesToAuthorities(String rolename) {
        if (rolename == null || rolename.isBlank()) {
            return Collections.emptyList();
        }

        return Arrays.stream(rolename.split(","))
                .map(String::trim)
                .filter(role -> !role.isEmpty())
                .map(role -> {
                    switch (role) {
                        case "超级管理员":
                            return new SimpleGrantedAuthority("ROLE_ADMIN");
                        case "普通用户":
                            return new SimpleGrantedAuthority("ROLE_USER");
                        default:
                            return new SimpleGrantedAuthority("ROLE_" + role);
                    }
                })
                .collect(Collectors.toList());
    }

}